package com.corn.zk.register;

import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * @author : Jim Wu
 * @version 1.0
 * @function :
 * @since : 2022/7/12 10:13
 */
@Slf4j
public class MyRegisterClient {

    public MyRegisterClient(String servers) {
        this.servers = servers;
    }

    public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
        MyRegisterClient registerClient = new MyRegisterClient(args[0]);
        registerClient.init();
        registerClient.register(args[1]);
        registerClient.doBusiness();
    }

    private final String servers;

    private final int sessionTimeout = 2000;

    private ZooKeeper zk;

    private final String registerZkPath = "/servers/";

    private final CountDownLatch awaitZkConnectedLatch = new CountDownLatch(1);

    private void init() throws IOException, InterruptedException {
        zk = new ZooKeeper(servers, sessionTimeout, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                if (event.getState() == Event.KeeperState.SyncConnected) {
                    awaitZkConnectedLatch.countDown();
                }
            }
        });

        if (zk.getState() == ZooKeeper.States.CONNECTING) {
            awaitZkConnectedLatch.await();
        }
    }

    private void register(String hostName) throws KeeperException, InterruptedException {
        Stat exists = zk.exists(registerZkPath + hostName, false);
        // 没有注册
        if (exists == null) {
            // 向zk进行注册 使用临时带序号节点
            zk.create(registerZkPath + hostName, hostName.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
            log.info("hostname:{} is online", hostName);
        }
    }

    private void doBusiness() {
        try {
            Thread.sleep(Integer.MAX_VALUE);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
